let resources = [];
let departments = [];
let resourceTypes = [];
let isEditMode = false;
let currentResourceId = null;
let currentResourceForAssign = null;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', async function() {
    // 先初始化权限管理器，确保权限判断正确
    if (window.AuthManager && window.AuthManager.getUserInfo()) {
        window.PermissionManager.init(window.AuthManager.getUserInfo());
    }

    // JWT认证检查
    if (!window.AuthManager || !AuthManager.isAuthenticated()) {
        showAccessDenied();
        return;
    }

    try {
        // 检查token有效性
        await AuthManager.verifyToken();
        
        // 在加载内容前进行权限检查
        if (window.PermissionManager && !window.PermissionManager.hasPermission('RESOURCE_MANAGEMENT', 'access')) {
            showAccessDenied();
            return;
        }

        // 权限通过，显示主要内容
        showMainContent();
        
        // 根据 'create' 权限控制创建按钮的显示
        if (window.PermissionManager && !window.PermissionManager.hasPermission('RESOURCE_MANAGEMENT', 'create')) {
             document.getElementById('createResourceBtn').style.display = 'none';
        }

        // 加载数据
        loadResources();
        loadDepartments();
        loadResourceTypes();

    } catch (e) {
        showAccessDenied();
        return;
    }
});

// 显示访问被拒绝
function showAccessDenied() {
    document.getElementById('accessDenied').style.display = 'block';
    document.getElementById('mainContent').style.display = 'none';
}

// 显示主要内容
function showMainContent() {
    document.getElementById('accessDenied').style.display = 'none';
    document.getElementById('mainContent').style.display = 'block';
}

// 检查资源管理权限
async function checkResourcePermission() {
    try {
        const user = AuthManager.getUserInfo();
        if (user) {
            // 只有管理员和部门管理员可以管理资源
            if (user.role !== 'ADMIN' && user.role !== 'DEPT_MANAGER') {
                document.getElementById('createResourceBtn').style.display = 'none';
            }
        }
    } catch (error) {
        console.error('检查权限失败:', error);
    }
}

// 加载资源数据
async function loadResources() {
    showLoading(true);
    try {
        const response = await fetch('/ercms/api/resources', {
            headers: AuthManager.getAuthHeaders()
        });
        const result = await response.json();
        if (result.success) {
            resources = result.data;
            renderResources();
        } else {
            alert('加载资源数据失败: ' + result.message);
        }
    } catch (error) {
        console.error('加载资源数据失败:', error);
        alert('加载资源数据失败');
    } finally {
        showLoading(false);
    }
}

// 加载部门数据
async function loadDepartments() {
    try {
        const response = await fetch('/ercms/api/departments', {
            headers: AuthManager.getAuthHeaders()
        });
        const result = await response.json();
        if (result.success) {
            departments = result.data;
            populateDepartmentSelects();
        }
    } catch (error) {
        console.error('加载部门数据失败:', error);
    }
}

// 加载资源类型数据
async function loadResourceTypes() {
    try {
        const response = await fetch('/ercms/api/resources/types', {
            headers: AuthManager.getAuthHeaders()
        });
        const result = await response.json();
        if (result.success) {
            resourceTypes = result.data;
            populateResourceTypeSelects();
        }
    } catch (error) {
        console.error('加载资源类型数据失败:', error);
    }
}

// 渲染资源列表
function renderResources() {
    const container = document.getElementById('resourceList');
    container.innerHTML = '';
    if (resources.length === 0) {
        container.innerHTML = `
            <div class="col-12 text-center text-muted">
                <i class="bi bi-gear" style="font-size: 3rem;"></i>
                <p class="mt-2">暂无资源数据</p>
            </div>
        `;
        return;
    }
    resources.forEach(resource => {
        const card = createResourceCard(resource);
        container.appendChild(card);
    });
}

// 创建资源卡片
function createResourceCard(resource) {
    const col = document.createElement('div');
    col.className = 'col-md-4 col-lg-3 mb-3';
    const statusClass = getStatusClass(resource.status);
    const statusText = getStatusText(resource.status);
    col.innerHTML = `
        <div class="card resource-card h-100">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start mb-2">
                    <h6 class="card-title mb-0">${resource.name}</h6>
                    <span class="badge status-badge ${statusClass}">${statusText}</span>
                </div>
                <p class="card-text text-muted small mb-2">
                    <i class="bi bi-tag"></i> ${resource.resourceTypeName || '未知类型'}
                </p>
                <p class="card-text text-muted small mb-2">
                    <i class="bi bi-building"></i> ${resource.departmentName || '未分配部门'}
                </p>
                ${resource.location ? `<p class="card-text text-muted small mb-2">
                    <i class="bi bi-geo-alt"></i> ${resource.location}
                </p>` : ''}
                ${resource.description ? `<p class="card-text small">${resource.description}</p>` : ''}
            </div>
            <div class="card-footer bg-transparent">
                <div class="btn-group btn-group-sm w-100">
                    <button class="btn btn-outline-primary" onclick="showEditResourceModal(${resource.id})">
                        <i class="bi bi-pencil"></i>
                    </button>
                    <button class="btn btn-outline-info" onclick="showAssignDepartmentModal(${resource.id})">
                        <i class="bi bi-building"></i>
                    </button>
                    <button class="btn btn-outline-danger" onclick="deleteResource(${resource.id})">
                        <i class="bi bi-trash"></i>
                    </button>
                </div>
            </div>
        </div>
    `;
    return col;
}

// 获取状态样式类
function getStatusClass(status) {
    switch (status) {
        case 'AVAILABLE': return 'status-available';
        case 'IN_USE': return 'status-in-use';
        case 'MAINTENANCE': return 'status-maintenance';
        case 'RETIRED': return 'status-retired';
        default: return 'status-available';
    }
}

// 获取状态文本
function getStatusText(status) {
    switch (status) {
        case 'AVAILABLE': return '可用';
        case 'IN_USE': return '使用中';
        case 'MAINTENANCE': return '维护中';
        case 'RETIRED': return '已报废';
        default: return '未知';
    }
}

// 填充部门选择框
function populateDepartmentSelects() {
    const departmentFilter = document.getElementById('departmentFilter');
    const resourceDepartment = document.getElementById('resourceDepartment');
    const assignDepartment = document.getElementById('assignDepartment');
    // 清空现有选项
    departmentFilter.innerHTML = '<option value="">所有部门</option>';
    resourceDepartment.innerHTML = '<option value="">请选择部门</option>';
    assignDepartment.innerHTML = '<option value="">请选择部门</option>';
    // 添加部门选项
    departments.forEach(dept => {
        const option = `<option value="${dept.id}">${dept.name}</option>`;
        departmentFilter.innerHTML += option;
        resourceDepartment.innerHTML += option;
        assignDepartment.innerHTML += option;
    });
}

// 填充资源类型选择框
function populateResourceTypeSelects() {
    const typeFilter = document.getElementById('typeFilter');
    const resourceType = document.getElementById('resourceType');
    // 清空现有选项
    typeFilter.innerHTML = '<option value="">所有类型</option>';
    resourceType.innerHTML = '<option value="">请选择资源类型</option>';
    // 添加资源类型选项
    resourceTypes.forEach(type => {
        const option = `<option value="${type.id}">${type.name}</option>`;
        typeFilter.innerHTML += option;
        resourceType.innerHTML += option;
    });
}

// 显示创建资源模态框
function showCreateResourceModal() {
    isEditMode = false;
    currentResourceId = null;
    document.getElementById('modalTitle').textContent = '创建资源';
    document.getElementById('resourceForm').reset();
    const modal = new bootstrap.Modal(document.getElementById('resourceModal'));
    modal.show();
}

// 显示编辑资源模态框
function showEditResourceModal(resourceId) {
    const resource = resources.find(r => r.id === resourceId);
    if (!resource) return;
    isEditMode = true;
    currentResourceId = resourceId;
    document.getElementById('modalTitle').textContent = '编辑资源';
    document.getElementById('resourceName').value = resource.name;
    document.getElementById('resourceType').value = resource.resourceType ? resource.resourceType.id : '';
    document.getElementById('resourceStatus').value = resource.status;
    document.getElementById('resourceDepartment').value = resource.departmentId || '';
    document.getElementById('resourceLocation').value = resource.location || '';
    document.getElementById('resourceDescription').value = resource.description || '';
    const modal = new bootstrap.Modal(document.getElementById('resourceModal'));
    modal.show();
}

// 保存资源
async function saveResource() {
    const formData = {
        name: document.getElementById('resourceName').value,
        resourceType: { id: parseInt(document.getElementById('resourceType').value) },
        status: document.getElementById('resourceStatus').value,
        departmentId: document.getElementById('resourceDepartment').value || null,
        location: document.getElementById('resourceLocation').value,
        description: document.getElementById('resourceDescription').value
    };
    if (!formData.name.trim()) {
        alert('请输入资源名称');
        return;
    }
    if (!formData.resourceType.id) {
        alert('请选择资源类型');
        return;
    }
    try {
        const url = isEditMode ? `/ercms/api/resources/${currentResourceId}` : '/ercms/api/resources';
        const method = isEditMode ? 'PUT' : 'POST';
        let requestUrl = url;
        if (!isEditMode) {
            requestUrl += '?createdBy=1'; // 假设当前用户ID
        }
        const response = await fetch(requestUrl, {
            method: method,
            headers: AuthManager.getAuthHeaders(),
            body: JSON.stringify(formData)
        });
        const result = await response.json();
        if (result.success) {
            alert(result.message);
            bootstrap.Modal.getInstance(document.getElementById('resourceModal')).hide();
            loadResources();
            loadDepartments();
            loadResourceTypes();
        } else {
            alert('操作失败: ' + result.message);
        }
    } catch (error) {
        console.error('保存资源失败:', error);
        alert('保存资源失败');
    }
}

// 删除资源
async function deleteResource(resourceId) {
    if (!confirm('确定要删除这个资源吗？删除后无法恢复！')) {
        return;
    }
    try {
        const response = await fetch(`/ercms/api/resources/${resourceId}`, {
            method: 'DELETE',
            headers: AuthManager.getAuthHeaders()
        });
        const result = await response.json();
        if (result.success) {
            alert(result.message);
            loadResources();
            loadDepartments();
            loadResourceTypes();
        } else {
            alert('删除失败: ' + result.message);
        }
    } catch (error) {
        console.error('删除资源失败:', error);
        alert('删除资源失败');
    }
}

// 显示分配部门模态框
function showAssignDepartmentModal(resourceId) {
    currentResourceForAssign = resourceId;
    const modal = new bootstrap.Modal(document.getElementById('assignDepartmentModal'));
    modal.show();
}

// 分配资源到部门
async function assignResourceToDepartment() {
    const departmentId = document.getElementById('assignDepartment').value;
    try {
        const response = await fetch(`/ercms/api/resources/${currentResourceForAssign}/assign-department?departmentId=${departmentId}`, {
            method: 'PUT',
            headers: AuthManager.getAuthHeaders()
        });
        const result = await response.json();
        if (result.success) {
            alert(result.message);
            bootstrap.Modal.getInstance(document.getElementById('assignDepartmentModal')).hide();
            loadResources();
            loadDepartments();
            loadResourceTypes();
        } else {
            alert('分配失败: ' + result.message);
        }
    } catch (error) {
        console.error('分配资源失败:', error);
        alert('分配资源失败');
    }
}

// 筛选资源
function filterResources() {
    const departmentFilter = document.getElementById('departmentFilter').value;
    const typeFilter = document.getElementById('typeFilter').value;
    const statusFilter = document.getElementById('statusFilter').value;
    const searchInput = document.getElementById('searchInput').value.toLowerCase();
    const filteredResources = resources.filter(resource => {
        // 部门筛选
        if (departmentFilter && resource.departmentId != departmentFilter) {
            return false;
        }
        // 类型筛选
        if (typeFilter && resource.resourceType && resource.resourceType.id != typeFilter) {
            return false;
        }
        // 状态筛选
        if (statusFilter && resource.status !== statusFilter) {
            return false;
        }
        // 搜索筛选
        if (searchInput && !resource.name.toLowerCase().includes(searchInput)) {
            return false;
        }
        return true;
    });
    renderFilteredResources(filteredResources);
}

// 渲染筛选后的资源
function renderFilteredResources(filteredResources) {
    const container = document.getElementById('resourceList');
    container.innerHTML = '';
    if (filteredResources.length === 0) {
        container.innerHTML = `
            <div class="col-12 text-center text-muted">
                <i class="bi bi-search" style="font-size: 3rem;"></i>
                <p class="mt-2">没有找到匹配的资源</p>
            </div>
        `;
        return;
    }
    filteredResources.forEach(resource => {
        const card = createResourceCard(resource);
        container.appendChild(card);
    });
}

// 显示/隐藏加载提示
function showLoading(show) {
    const spinner = document.getElementById('loadingSpinner');
    if (show) {
        spinner.classList.remove('d-none');
    } else {
        spinner.classList.add('d-none');
    }
}

// 新建资源类型相关
function showCreateResourceTypeModal() {
    document.getElementById('resourceTypeForm').reset();
    const modal = new bootstrap.Modal(document.getElementById('resourceTypeModal'));
    modal.show();
}

async function saveResourceType() {
    const name = document.getElementById('resourceTypeName').value.trim();
    const desc = document.getElementById('resourceTypeDesc').value.trim();
    if (!name) {
        alert('请输入类型名称');
        return;
    }
    try {
        const response = await fetch('/ercms/api/resources/types', {
            method: 'POST',
            headers: AuthManager.getAuthHeaders(),
            body: JSON.stringify({ name: name, description: desc })
        });
        const result = await response.json();
        if (result.success) {
            alert('资源类型创建成功');
            bootstrap.Modal.getInstance(document.getElementById('resourceTypeModal')).hide();
            loadResourceTypes();
        } else {
            alert('创建失败: ' + result.message);
        }
    } catch (e) {
        alert('创建失败');
    }
} 